﻿Imports Microsoft.Practices.Composite.Wpf.Regions
Imports Microsoft.Practices.Composite.Regions
Imports Infragistics.Windows.Controls
Imports System.Collections.Specialized
Imports System.ComponentModel
Imports Infragistics.Windows.DockManager
Imports Infragistics.Windows.Ribbon
Imports System.Windows.Controls

Namespace RegionAdapters

    Public Class GridRegionAdapter
        Inherits RegionAdapterBase(Of Grid)

        Private m_regionTarget As Grid

        Protected Overrides Sub Adapt(ByVal region As Microsoft.Practices.Composite.Regions.IRegion, ByVal regionTarget As Grid)
            m_regionTarget = regionTarget
            'If control has child items, move them to the region and then bind control to region. Can't set ItemsSource if child items exist.
            If regionTarget.Children.Count > 0 Then
                For Each childItem In regionTarget.Children
                    region.Add(childItem)
                Next
            End If
            regionTarget.Children.Clear()
            AddHandler region.ActiveViews.CollectionChanged, AddressOf OnActiveViewsChanged
            For Each view In region.ActiveViews
                regionTarget.Children.Add(view)
            Next
        End Sub

        Private Sub OnActiveViewsChanged(ByVal sender As Object, ByVal e As NotifyCollectionChangedEventArgs)
            Select Case e.Action
                Case NotifyCollectionChangedAction.Add
                    For Each v In e.NewItems
                        m_regionTarget.Children.Add(v)
                    Next
                Case NotifyCollectionChangedAction.Remove
                    For Each v In e.OldItems
                        m_regionTarget.Children.Remove(v)
                    Next
            End Select
        End Sub

        Protected Overrides Function CreateRegion() As Microsoft.Practices.Composite.Regions.IRegion
            Return New AllActiveRegion
        End Function

    End Class

End Namespace